/*
 * @Author: mikey.zhaopeng
 * @Date:   2016-01-14 16:12:19
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 16:53:45
 */

'use strict';
/**
 * [视频上传]
 */
define([
    '../base/baseView',
    '../model/video',
    'fileinput',
    'jquery-html5Validate'
], function(
    BaseView,
    videoModel
) {
    function UploadVideo() {
        BaseView.apply(this, arguments);
        var self = this;
        this.init = function() {
            self.$el = $('#upload-video-modal');
            self.$videoEl = $('#video-container');
            self.render();
            self.event();
        }

        this.event = function() {
            self.$videoEl.off('uploadVideo').on('uploadVideo', $.proxy(self.openUploadModal, self));
            $('#modal-btn-upload').off('click').on('click', $.proxy(self.uploadVideo, self));
            $('#modal-btn-edit').off('click').on('click', $.proxy(self.editVideo, self));
            $('#modal-btn-finish').off('click').on('click', $.proxy(self.closeUploadModal, self));
        }

        this.closeUploadModal = function(e) {
            $('#video-container .btn-search').trigger('click');
        }

        /**
         * [editVideo 进入视频打标签的 view ]
         * @param  {[type]} e [description]
         * @return {[type]}   [description]
         */
        this.editVideo = function(e) {
            var self = this;
            var filesLen = $('.file-preview-thumbnails .file-preview-frame .file-upload-indicator').length;
            var successFilesLen = $('.file-preview-thumbnails .file-preview-frame:not(.upload-error-msg) .file-upload-indicator .text-success').length;
            if (filesLen === 0) {
                self.showMsgs(I18N.getText('videoManage', 'noEditVideo'), 'info');
                return false;
            }
            if (filesLen !== successFilesLen) {
                self.showMsgs(I18N.getText('videoManage', 'deleteFailed'), 'info');
                return false;
            }

            var mids = [];
            $('.file-preview-thumbnails .file-preview-frame:not(.add-image-btn)').each(function() {
                mids.push($(this).data('mId'));
            });
            self.$el.modal('hide');
            window.localStorage.setItem('videEditIds', mids.join(','));
            setTimeout(function() {
                window.location.hash = '!videoEdit';
            }, 600);
        }

        this.render = function() {
            videoModel.queryApps(function(apps) {
                var $app = self.$el.find('select[name="modal-app-select"]');
                self._.each(apps, function(app) {
                    var optionHtml = '<option value="' + app.fbConnectionObjectId + '"> ' + app.name + ' </option>';
                    $app.append(optionHtml);
                });
                $app.select2();
            });
        }

        this.uploadVideo = function(e) {
            var errorFilesLen = $('.file-preview-thumbnails .file-preview-frame.file-preview-error').length;
            if (errorFilesLen > 0) {
                self.errorMsg(I18N.getText('videoManage', 'msgPlsdelete'));
                return;
            }

            var uploadFileLen = $('.file-preview-thumbnails .file-preview-frame .file-thumbnail-footer').length;
            if (uploadFileLen == 0) {
                self.errorMsg(I18N.getText('videoManage', 'msgPlsupload'));
                return;
            }

            var $app = self.$el.find('select[name="modal-app-select"]');
            if ($app.val() == '') {
                $app.next().testRemind(I18N.getText('videoManage', 'optionPlsApp'));
                return;
            }
            $("#input-video").fileinput('upload');
        }

        this.openUploadModal = function(e) {
            self.initUploadI18n();
            self.$el.modal({
                backdrop: 'static',
                keyboard: false
            });
            self.$el.modal('show');
            self.$el.find('.modal-alert').empty();
            $('#modal-btn-finish').addClass('hide');
            $('#modal-btn-edit').addClass('hide');
            $('#modal-btn-upload').removeClass('hide');
            $('select[name=modal-app-select]').val('').trigger('change');
            self.$el.addClass('no-picture-upload'); //添加背景 hover
            var $uploadArea = self.$el.find('.upload-area');
            $uploadArea.html('<input id="input-video" type="file" name="files"  multiple=true class="file-loading" accept="video/*">');
            var $inputUpload = $("#input-video");

            $inputUpload.fileinput('destroy');
            $inputUpload.fileinput({
                language: (localStorage.language == 'en-us' ? 'en-us' : 'zh'),
                showCaption: false,
                showRemove: false,
                showUpload: false,
                showCancel: false,
                uploadAsync: false,
                uploadUrl: window.cors_config.uplodeVideo,
                allowedFileExtensions: ["mp4", "avi"],
                maxFileCount: 50, //文件个数
                maxFileSize: 1024 * 1024 * 1024, //支持的最大文件大小
                browseClass: 'btn btn-default',
                uploadClass: 'btn btn-primary',
                showPreview: true,
                msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
                previewSettings: {
                    video: {
                        width: "150px",
                        height: "100px"
                    },
                },
                fileActionSettings: {
                    uploadClass: 'hide',
                    removeTitle: I18N.getText('videoManage', 'delete'),
                    indicatorNewTitle: '还没有开始上传',
                    indicatorSuccessTitle: '上传完成',
                    indicatorErrorTitle: '上传错误',
                    indicatorLoadingTitle: '上传中 ...'
                },
                layoutTemplates: {
                    actionDelete: '<button type="button" class="kv-file-remove close" title="{removeTitle}"{dataUrl}{dataKey}><span aria-hidden="true">×</span></button>',
                    footer: '<div class="file-thumbnail-footer">\n' +
                        '    <div class="file-caption-name" style="width:{width}">{caption}</div>\n' +
                        '    {actions}\n' +
                        '</div>'
                },
                uploadExtraData: function() {
                    var fileNames = [];
                    $uploadArea.find('.file-thumbnail-footer>.file-caption-name').each(function() {
                        var title = $(this).text().trim();
                        fileNames.push(title);
                    });

                    var $appSelect = $('select[name=modal-app-select]');
                    var appId = $appSelect.val();
                    var appName = $appSelect.find('option:checked').text().trim();
                    if (appId == '') {
                        appName = '';
                    }
                    window.localStorage.setItem('videEditAppId', appId);
                    window.localStorage.setItem('videEditAppName', appName);
                    return {
                        appId: appId,
                        appName: appName,
                        fileNames: fileNames
                    };
                },
                ajaxSettings: {
                    xhrFields: {
                        withCredentials: true
                    }
                }
            }).on('filebatchuploadcomplete', function(event, files, extra) {
                var allNum = $('.file-preview .file-preview-frame.file-preview-success').length;
                var successNum = $('.file-preview .file-preview-frame.file-preview-success .file-icon-large.text-success').length;
                if (successNum > 0 && allNum == successNum) {
                    // $('#btn-next-step').trigger('click');
                }
                var process = $('.progress-bar.progress-bar-success').html().trim();
                if (process == "100%") {}
                $('.kv-upload-progress').hide();
                $('#modal-btn-upload').addClass('hide');
                $('#modal-btn-edit').removeClass('hide');
                $('#modal-btn-finish').removeClass('hide');
                $('.file-preview-frame.add-image-btn').addClass('hide');
                $('#btn-next-step').removeClass('hide');
                $('#cancel-btn').removeClass('hide');
            }).on('filebatchuploadsuccess', function(event, data, previewId, index) {
                if (data.response.flag === 'success') {
                    self.showUploadMsg(null, data.response.data);
                } else if (data.response.flag === 'fail') {
                    self.showUploadMsg(data.response.msg);
                } else {}
                $('#cancel-btn').off('click').on('click', function() {
                    setTimeout(function() {
                        $('#query-btn').trigger('click')
                    }, 200)
                });

            }).on('filepreajax', function(event, previewId, index) {
                var errorFilesLen = $('.file-preview-thumbnails .file-preview-frame .file-upload-indicator .text-danger').length;
                if (errorFilesLen > 0) {
                    $inputUpload.fileinput('cancel');
                    setTimeout(function() {
                        $('.fileinput-cancel-button').trigger('click');
                    }, 200);
                    return {
                        message: I18N.getText('videoManage', 'msgPlsdelete')
                    };
                }
            }).on('filepreremove', function(event) {
                $('.file-drop-zone .tooltip').remove();

            }).on('fileloaded', function(event, file, previewId, index, reader) {
                $uploadArea.find('.add-image-btn').remove();
                $uploadArea.find('.file-preview-thumbnails').append('<div class="file-preview-frame add-image-btn"> <i class="glyphicon glyphicon-plus"></i> </div>');
                setTimeout(function() {
                    $uploadArea.find('.add-image-btn .glyphicon-plus').unbind('click').on('click', function() {
                        var fileInput = document.getElementById("input-video");
                        fileInput.click(); //加一个触发事件
                    });
                    self.showMsgs(I18N.getText('videoManage', 'selected') + ' <span class="image-count">'  + $uploadArea.find('.file-preview-frame .file-thumbnail-footer').length + '</span> ' +I18N.getText('videoManage', 'videos'));
                    $uploadArea.find('.kv-fileinput-error.file-error-message').hide()
                    $('.file-preview-thumbnails img').each(function() {
                        if (($(this)[0].naturalWidth > 0) && ($(this)[0].naturalWidth == $(this)[0].naturalHeight)) {
                            $(this).width(100)
                        }
                    });
                }, 200);

                if (file.type.indexOf('video/') == 0) {
                    var reader = new FileReader();
                    reader.onload = (function(f) {
                        return function(e) {
                            $('#' + previewId).data('base64', e.target.result)
                        };
                    })(file);
                    reader.readAsDataURL(file);
                } else {
                    // $('#' + data.id).remove();
                }
                self.$el.removeClass('no-picture-upload'); //文件加载后移除背景 hover
                self.$el.find('.modal-body').unbind('click');
                $('#modal-btn-preview').removeClass('hide');



            }).on('filereset', function(event, previewId) {
                $('#upload-video-modal .modal-alert').html('');
                $('#upload-video-modal').addClass('no-picture-upload'); //input reset 后添加背景 hover
                $('#modal-btn-preview').addClass('hide');
            }).on('fileuploaderror', function(event, data, previewId, index) {
                if (data.ind) {
                    return;
                }
                if (data.files) {
                    if (data.files.length <= 50) {
                        if (data.files[data.index].type.startsWith('video/')) {

                        } else {
                            $('#' + data.id).remove();
                        }

                    } else {
                        self.kit.alert2(I18N.getText('videoManage', 'maxSelectedVideos'));
                        $inputUpload.fileinput('reset');
                    }
                }
                setTimeout(function() {
                    $uploadArea.find('.kv-fileinput-error.file-error-message').hide()
                }, 440);
            }).on('fileuploaderror', function(event, previewId) {
                console.log('fileuploaderror');
                $uploadArea.find('.file-preview-frame.btn.disabled.file-preview-error').remove();
                if ($uploadArea.find('.file-preview-frame .file-thumbnail-footer').length == 0) {
                    $uploadArea.find('.add-image-btn').remove();
                    $inputUpload.fileinput('reset');
                    $('#upload-video-modal .modal-alert').text('');
                }
                // common.msgs.pop_up('上传文件错误!请重新选择!', 'error');
                setTimeout(function() {
                    // $('#btn-upload').trigger('click');
                }, 200);
            }).on('filecleared', function(event, previewId) {}).on('filedeleted', function(event, previewId) {}).on('filesuccessremove', function(event, previewId) {
                $('.tooltip.fade.top.in').remove()
            }).on('fileerror', function(event, previewId) {
                $uploadArea.find('.kv-fileinput-error.file-error-message').hide()
            }).on('filereset', function(event, previewId) {
                setTimeout(function() {
                    self.resetModalBodyInput();
                }, 200);
            }).on('fileremoved', function(event, previewId) {
                if ($uploadArea.find('.file-preview-frame .file-thumbnail-footer').length == 0) {
                    $uploadArea.find('.add-image-btn').remove();
                    $inputUpload.fileinput('reset');
                    $('#upload-video-modal .modal-alert').text('');
                } else {
                    self.showMsgs(I18N.getText('videoManage', 'selected') + '<span class="image-count">  ' + $uploadArea.find('.file-preview-frame .file-thumbnail-footer').length + '  </span>'+I18N.getText('videoManage', 'videos'));
                }

            })
            self.resetModalBodyInput();
        }


        this.resetModalBodyInput = function() {
            $("#upload-video-modal .modal-body").unbind('click').on('click', function() {
                var fileInput = document.getElementById("input-video");
                fileInput.click(); //加一个触发事件
            });
        }



        /**
         * [showUploadMsg 显示错误信息]
         * @param  {[type]} errorMsg          [错误信息]
         * @param  {[type]} fileErrors   [文件错误信息,有多个]
         * @return {[type]}              [description]
         */
        this.showUploadMsg = function(errorMsg, fileErrors) {
            setTimeout(function() {
                if ((errorMsg && errorMsg.length > 0) || (fileErrors && fileErrors.length > 0)) {
                    if (errorMsg && errorMsg.length > 0) {
                        self.errorMsg((errorMsg) || I18N.getText('imageManage', 'plsChooseUploadFile'));
                        $("#input-video").fileinput('refresh');
                        return;
                    } else {
                        var msg = $(".kv-fileinput-error.file-error-message");
                        var msgHtml = '<span class="close kv-error-close">×</span><ul>';
                        var errorNum = 0;
                        var totalNum = 0;
                        var filePreview = $('.file-preview-thumbnails .file-preview-frame:not(.add-image-btn)');
                        if (fileErrors && fileErrors.length > 0) {
                            totalNum = fileErrors.length;
                            self._.each(fileErrors, function(file, idx) {
                                if (file && file.mongodbId) {
                                    $(filePreview[idx]).data('mId', file.mongodbId);
                                } else {
                                    $(filePreview[idx]).data('mId', 0);
                                }
                                if (file && file.msg && file.msg.length > 0) {
                                    $(filePreview[idx]).addClass('upload-error-msg').addClass('file-preview-error');
                                    $(filePreview[idx]).attr('title', file.msg);
                                    $(filePreview[idx]).tooltip({
                                        placement: 'top'
                                    });
                                    errorNum++;
                                }
                            });
                        }
                        msgHtml = msgHtml + '</ul>'
                        if (errorNum > 0) {
                            self.errorMsg(I18N.getText('videoManage', 'success') + '<span class="image-count">' + (totalNum - errorNum) + '</span>' + I18N.getText('videoManage', 'item') + '  (' + '<span class="image-count">' + errorNum + '</span>' + I18N.getText('videoManage', 'fail') + ')', 'error')
                        } else {
                            self.okMsg(I18N.getText('videoManage', 'success') + '<span class="image-count">' + (totalNum - errorNum) + '</span>' + I18N.getText('videoManage', 'item'))
                        }

                    }
                }
            }, 300);
        }


        /*
         @信息提示
         $.msg:文本
         $.type: 类型
         $.cb: 回调
         */
        this.showMsgs = function(msg, type, cb) {
            var color = type == 'error' ? '#f00' : '#333';
            var uploadAdimageModal = $('#upload-video-modal'),
                modalAlert = $('.modal-alert', uploadAdimageModal);
            modalAlert.html(msg).css('color', color);
        }



        /**
         * { 成功提醒 }
         *
         * @method     okMsg
         * @param      {<type>}  msg     { description }
         */
        this.okMsg = function(msg) {
                showTip({
                    time: 5, // 永不消失， 如果需要定时消失，这里写数字，30 （表示30s后自动消失）
                    type: "success",
                    bind: $("#upload-video-modal .modal-body"), //显示在哪里，DOM jquery对象
                    content: msg,
                    icon: "<i class='glyphicon glyphicon-flag'></i>",
                    close: false
                });
            },
            /**
             * { 错误提醒 }
             *
             * @method     errorMsg
             * @param      {<type>}  msg     { description }
             */
            this.errorMsg = function(msg) {
                showTip({
                    time: 5, // 永不消失， 如果需要定时消失，这里写数字，30 （表示30s后自动消失）
                    type: "error",
                    bind: $("#upload-video-modal .modal-body"), //显示在哪里，DOM jquery对象
                    content: msg,
                    icon: "<i class='glyphicon glyphicon-flag'></i>",
                    close: false
                });
            },

            this.initUploadI18n = function() {
                if (localStorage.language == 'en-us') {
                    $.fn.fileinputLocales['en-us'] = {
                        fileSingle: 'file',
                        filePlural: 'files',
                        browseLabel: 'Browse &hellip;',
                        removeLabel: 'Remove',
                        removeTitle: 'Clear selected files',
                        cancelLabel: 'Cancel',
                        cancelTitle: 'Abort ongoing upload',
                        uploadLabel: 'Upload',
                        uploadTitle: 'Upload selected files',
                        msgZoomTitle: 'View details',
                        msgZoomModalHeading: 'Detailed Preview',
                        msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
                        msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
                        msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
                        msgFileNotFound: 'File "{name}" not found!',
                        msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
                        msgFileNotReadable: 'File "{name}" is not readable.',
                        msgFilePreviewAborted: 'File preview aborted for "{name}".',
                        msgFilePreviewError: 'An error occurred while reading the file "{name}".',
                        msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
                        msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
                        msgValidationError: 'File Upload Error',
                        msgLoading: 'Loading file {index} of {files} &hellip;',
                        msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
                        msgSelected: '{n} {files} selected',
                        msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
                        msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
                        msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
                        msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
                        msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
                        dropZoneTitle: '<p class="upload-icon"><img src="./imgs/upload.png"></p><p>click & drop files here<p><button class="upload-button" type="button">upload</button></p><p>Only support mp4/avi format</p>',
                    };
                } else {

                    $.fn.fileinputLocales['zh'] = {
                        fileSingle: '文件',
                        filePlural: '个文件',
                        browseLabel: '选择 &hellip;',
                        removeLabel: '移除',
                        removeTitle: '清除选中文件',
                        cancelLabel: '取消',
                        cancelTitle: '取消进行中的上传',
                        uploadLabel: '上传',
                        uploadTitle: '上传选中文件',
                        msgZoomTitle: '查看详情',
                        msgZoomModalHeading: '详细预览',
                        isThirdPic: false,
                        msgSizeTooLarge: '文件 "{name}" (<b>{size} KB</b>) 超过了允许大小 <b>{maxSize} KB</b>.',
                        msgFilesTooLess: '你必须选择最少 <b>{n}</b> {files} 来上传. ',
                        msgFilesTooMany: '选择的上传文件个数 <b>({n})</b> 超出最大文件的限制个数 <b>{m}</b>.',
                        msgFileNotFound: '文件 "{name}" 未找到!',
                        msgFileSecured: '安全限制，为了防止读取文件 "{name}".',
                        msgFileNotReadable: '文件 "{name}" 不可读.',
                        msgFilePreviewAborted: '取消 "{name}" 的预览.',
                        msgFilePreviewError: '读取 "{name}" 时出现了一个错误.',
                        msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.',
                        msgInvalidFileExtension: '过滤掉 "{name}". 只支持 "{extensions}" 的文件扩展名.',
                        msgValidationError: '文件错误',
                        msgLoading: '加载第 {index} 文件 共 {files} &hellip;',
                        msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.',
                        msgSelected: '{n} {files} 选中',
                        msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.',
                        msgImageWidthSmall: '宽度的图像文件的"{name}"的必须是至少{size}像素.',
                        msgImageHeightSmall: '图像文件的"{name}"的高度必须至少为{size}像素.',
                        msgImageWidthLarge: '宽度的图像文件"{name}"不能超过{size}像素.',
                        msgImageHeightLarge: '图像文件"{name}"的高度不能超过{size}像素.',
                        dropZoneTitle: '<p class="upload-icon"><img src="./imgs/upload.png"></p><p>视频拖放到这里</p><p>或</p><p><button class="upload-button" type="button">上传</button></p><p>只支持 mp4 avi 格式的视频.</p>',
                        slugCallback: function(text) {
                            return text ? text.split(/(\\|\/)/g).pop().replace(/[^\w\u4e00-\u9fa5\-.\\\/ ]+/g, '') : '';
                        },
                        fileActionSettings: {
                            removeTitle: '删除文件',
                            uploadTitle: '上传文件',
                            indicatorNewTitle: '没有上传',
                            indicatorSuccessTitle: '上传',
                            indicatorErrorTitle: '上传错误',
                            indicatorLoadingTitle: '上传 ...'
                        }
                    };
                }

            }





    };
    return new UploadVideo();
});
